import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import {
  Form,
  Input,
  InputNumber,
  Radio,
  Modal,
  Select,
  Upload,
  message,
  Space,
  Col,
  Row,
  Card,
  Descriptions, Button
} from 'antd'
import {t, Trans} from "@lingui/macro"
import { Timeline } from 'antd';
import TextArea from "antd/es/input/TextArea";
import {getCurrentUser} from "../../../utils/auth"
import UserSelectModal from "./UserSelectModal";

const { Option } = Select;
const FormItem = Form.Item

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
}

class ApprovalProcessOrderInfoModal extends PureComponent {
  formRef = React.createRef()

  state = {
    value: [],
    loading: false, //上传 loading
    userModalVisible: false,
    currentNode: null, //转交的时候暂存当前节点信息的
  };

  get userModalProps() {
    const { userOptions, onApproval } = this.props
    let ref = this
    return {
      visible: this.state.userModalVisible,
      destroyOnClose: true,
      maskClosable: false,
      userOptions:userOptions,
      title: `${
        t`Select user`
      }`,
      onOk(payload) {
        ref.setState({userModalVisible: false})
        ref.formRef.current.validateFields()
          .then(values => {
            onApproval({id:ref.state.currentNode.id, status: 40, reply: values.reply, nextUserId: payload.userId});
          })
          .catch(errorInfo => {
            console.log(errorInfo)
          })
      },
      onCancel() {
        console.log("执行了取消操作")
        ref.setState({userModalVisible: false})
      },
    }
  }

  handleOk = (node, status) => {
    const { item = {}, onApproval,onCancel } = this.props
    this.formRef.current.validateFields()
      .then(values => {
        onApproval({id:node.id, status: status, reply: values.reply});
      })
      .catch(errorInfo => {
        console.log(errorInfo)
      })
  }

  //转交
  handlePassOn = (node, status) => {
    this.setState({userModalVisible: true,currentNode:node})
  }

  handleReject = () => {
    //拒绝审批
  }
  handleCancel = () => {
    const { item = {}, onApproval,onCancel } = this.props
    onCancel();
  }

  render() {
    const { item = {}, onApproval, form, userOptions=[], ...modalProps } = this.props
    const contentList = JSON.parse(item.content ? item.content : '[]')
    const contentItemList = [];
    let users = {}
    let currentNode = null;
    userOptions.forEach(user=>{
      users[user.id] = user.username;
    })
    // contentItemList.push(<><Row><Col span={8}>审批类型</Col><Col span={16}>{item.approvalProcessName}</Col></Row></>)
    contentItemList.push(<Descriptions.Item label={'审批类型'} span={3} >{item?.approvalProcessName}</Descriptions.Item>)
    contentItemList.push(<Descriptions.Item label={'创建时间'} span={3} >{item?.createdTime}</Descriptions.Item>)
    contentList.forEach((d)=>{
      console.log(d)
      let content = d.type=='editor' ? <div dangerouslySetInnerHTML={{__html:d.content}} /> : d.content
      contentItemList.push(<Descriptions.Item label={d.title} span={3}>{content}</Descriptions.Item>)
    });

    //计算节点信息
    let nodeList = [];
    let nodes = item.nodes ? item.nodes : [];
    let isCurrentApproval = false
    let currentUser = getCurrentUser()
    let footerButtons = []
    nodes.forEach(node=>{
      if(node.status == 10 && node.userId == currentUser.id) {
        isCurrentApproval = true
      }

      let color = 'gray';
      // let currentNode = null;
      switch (node.status) {
        case 30:
        case 40:
          color = "green";
          break;
        case 20:
          color = "red";
          break;
        case 10:
          currentNode = node
          color = "blue";
          break;
        default:
          color = "gray";
          break;
      }
      nodeList.push(<Timeline.Item color={color}>
        <p>{node.approvalTime} {users[node.userId]} {node.statusName}</p>
        <p>{node.reply}</p>
      </Timeline.Item>)
    })

    if(isCurrentApproval) {
      footerButtons = [
        <Button key="back"  onClick={()=>this.handleOk(currentNode, 20)} >
          拒绝
        </Button>,
        <Button key="submit" type="primary" onClick={()=>this.handleOk(currentNode, 30)}>
          通过
        </Button>,
        <Button key="passOn" type="primary" onClick={()=>this.handlePassOn(currentNode, 40)}>
          转交
        </Button>,
        <Button key={"cancel"} onClick={this.handleCancel}>
          取消
        </Button>,
      ]
    } else {
      footerButtons = [
        <Button onClick={this.handleCancel}>
          取消
        </Button>,
      ]
    }

    return (
      <>
        <Modal width={'400px'} {...modalProps}
               footer={footerButtons}
        >

          <Descriptions title=""  >
            {contentItemList}

            <Descriptions.Item label={'审批流'} span={3}>
              <Timeline>
                <Timeline.Item color="green">{item.createdTime} {users[item.appleUserId]} 提交审批 </Timeline.Item>
                {nodeList}
              </Timeline>
            </Descriptions.Item>
          </Descriptions>

          <Form ref={this.formRef} name="control-ref" initialValues={{ ...item }} layout="horizontal">
            <FormItem name='reply' rules={[{ required: false }]}>
              <TextArea placeholder={t`Please input reply`} />
            </FormItem>
          </Form>
        </Modal>

        <UserSelectModal {...this.userModalProps} ></UserSelectModal>
      </>

    )
  }
}

ApprovalProcessOrderInfoModal.propTypes = {
  type: PropTypes.string,
  item: PropTypes.object,
  onApproval: PropTypes.func,
  userOptions: PropTypes.any
}

export default ApprovalProcessOrderInfoModal

